#include "SylphSystem.h"
#include "Ogre.h"

namespace Sylph
{
	///////////////////////////////////////////////////////////////////////
	SylphSystem::SylphSystem()
		: mRoot(NULL)
		, mTimer(NULL)
	{

	}

	//---------------------------------------------------------------------
	SylphSystem::~SylphSystem()
	{
		SAFE_DELETE(mRoot);
		SAFE_DELETE(mTimer);
	}

	//---------------------------------------------------------------------
	void SylphSystem::init(const SylphSystem::ConfigOptions& options)
	{
		mRoot = new Ogre::Root(options.pluginFile,"",options.logFile);
		mRoot->setRenderSystem(mRoot->getRenderSystemByName(options.renderSystem));
		mRoot->initialise(false);

		mTimer = new Ogre::Timer();
		mCurrentTime = mTimer->getMicroseconds();
	}

	//---------------------------------------------------------------------
	void SylphSystem::shutDown()
	{
		mRoot->shutdown();
		SAFE_DELETE(mTimer);
		SAFE_DELETE(mRoot);
	}

	//---------------------------------------------------------------------
	void SylphSystem::createWindow(const SylphSystem::WindowOptions& options)
	{
		mRoot->createRenderWindow(options.name, options.width, options.height, options.isFull);
	}

	//---------------------------------------------------------------------
	void SylphSystem::locateResources(const std::string& resourceConfigFile)
	{
		// load resource paths from config file
		Ogre::ConfigFile cf;
		cf.load(resourceConfigFile);

		Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
		Ogre::String sec, type, arch;

		// go through all specified resource groups
		while (seci.hasMoreElements())
		{
			sec = seci.peekNextKey();
			Ogre::ConfigFile::SettingsMultiMap* settings = seci.getNext();
			Ogre::ConfigFile::SettingsMultiMap::iterator i;

			// go through all resource paths
			for (i = settings->begin(); i != settings->end(); i++)
			{
				type = i->first;
				arch = i->second;

				Ogre::ResourceGroupManager::getSingleton().addResourceLocation(arch, type, sec);
			}
		}
	}

	//---------------------------------------------------------------------
	void SylphSystem::loadResources()
	{
		Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
	}
	//---------------------------------------------------------------------
	bool SylphSystem::run()
	{
		unsigned long lastTime = mCurrentTime;
		mCurrentTime = mTimer->getMicroseconds();

		// Clear event times
		mRoot->clearEventTimes();

		//Pump messages in all registered RenderWindow windows
		Ogre::WindowEventUtilities::messagePump();

		if(mRoot->renderOneFrame(mCurrentTime - lastTime))
		{
			return true;
		}
		else
			return false;

		return true;
	}
}